package cn.tedu.coolshark.controller;

import cn.tedu.coolshark.mapper.ProductMapper;
import cn.tedu.coolshark.pojo.dto.ProductDto;
import cn.tedu.coolshark.pojo.dto.ProductUpdateDto;
import cn.tedu.coolshark.pojo.entity.Product;
import cn.tedu.coolshark.pojo.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/product/")
public class ProductController {
    @Value("${dirPath}")
    private String dirPath;

    @Autowired(required = false)
    ProductMapper mapper;
    @RequestMapping("insert")
    public void insert(@RequestBody ProductDto product){
        System.out.println("product = " + product);

        Product p = new Product();
        BeanUtils.copyProperties(product,p);
        p.setCreated(new Date());
        //保存到数据库中
        mapper.insert(p);
    }
    @RequestMapping("select")
    public List<ProductAdminVo> select(){

        return mapper.select();
    }
    @RequestMapping("delete")
    public void delete(int id){
        //得到图片路径 然后删除图片
        String url = mapper.selectUrlById(id);
        new File(dirPath+url).delete();
        //删除数据库数据
        mapper.deleteById(id);
    }
    @RequestMapping("selectById")
    public ProductUpdateVo selectById(int id){
        return mapper.selectById(id);
    }

    @RequestMapping("update")
    public void update(@RequestBody ProductUpdateDto product){
        System.out.println("product = " + product);
        mapper.update(product);
    }
    @RequestMapping("selectForIndex")
    public List<ProductIndexVo> selectForIndex(){
        return mapper.selectForIndex();
    }

    @RequestMapping("selectForTop")
    public List<ProductTopVo> selectForTop(){
        return mapper.selectForTop();
    }
    @RequestMapping("selectByCid")
    public List<ProductIndexVo> selectByCid(int id){
        return mapper.selectByCid(id);
    }
    @RequestMapping("selectByWd")
    public List<ProductIndexVo> selectByWd(String wd){
        return mapper.selectByWd(wd);
    }

    @RequestMapping("selectForDetailById")
    public ProductDetailVo selectForDetailById(int id, HttpSession session){
        // 通过viewid从会话对象中获取字符串, 如果取到的是null代表第一次浏览,不是null代表不是第一次
        String info = (String) session.getAttribute("view"+id);
        if (info==null){
            //如果是第一次 需要把字符串保存到会话对象中 并且让浏览量+1
            session.setAttribute("view"+id,"visited");
            //让浏览量+1
            mapper.updateViewCountById(id);
        }
        return mapper.selectForDetailById(id);
    }


}
